﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using ServerLibrary.Abstract;

namespace ServerLibrary.Concrete
{
    /// <summary>
    /// TODO: Implements file handler.
    /// </summary>
    public class FileHandler : IHandler
    {
        private List<string> fileTypes;
        private FileStream requestedFile;

        public FileHandler()
        {
            fileTypes = new List<string>(new string[] { ".html", ".htm", ".jpg", ".jpeg", ".png", ".gif", ".css", ".js" });
            requestedFile = null;
        }

        public int Handle(string fileName, out byte[] file, out string contentType)
        {
            int httpStatus = 200;
            contentType = "";
            file = new byte[1];
            string fileExtension = fileName.Substring(fileName.LastIndexOf('.'));
            foreach (string fileType in fileTypes)
            {
                if (fileType == fileExtension)
                {
                    try
                    {
                        requestedFile = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read);
                        file = new byte[requestedFile.Length];
                        requestedFile.Read(file, 0, file.Length);
                        requestedFile.Close();
                        break;
                    }
                    catch (IOException)
                    {
                        httpStatus = 404;
                        break;
                    }
                }

            }
            contentType = GetContentType(fileExtension);
            if (contentType == "")
                httpStatus = 404;

            return httpStatus;
        }

        /// <summary>
        /// Gets content type
        /// </summary>
        /// <param name="fileExtension">File extension</param>
        /// <returns>Content type or ""</returns>
        public string GetContentType(string fileExtension)
        {
            string contentType;
            switch (fileExtension)
            {
                case ".htm":
                case ".html":
                    contentType = "text/html";
                    break;
                case ".jpg":
                    contentType = "image/jpeg";
                    break;
                case ".jpeg":
                case ".png":
                case ".gif":
                    contentType = "image/" + fileExtension.Substring(1);
                    break;
                case ".css":
                    contentType = "text/stylesheet";
                    break;
                case ".js":
                    contentType = "text/javascript";
                    break;
                default:
                    contentType = "";
                    break;
            }
            return contentType;
        }
    }
}
